<template>
    <div class="flex-container">
        <div class="map-container">
            <img :src="mapSrc" class="map-image" alt="Campus Map" @click="handleClick" />
            <div v-for="(point, index) in points" :key="index" class="marker"
                :style="{ left: point.x + 'px', top: point.y + 'px' }"></div>
            <div v-for="facility in facilities" :key="facility.id" class="facility" :style="getFacilityStyle(facility)">
                <div class="facility-name">{{ facility.name }}</div>
            </div>
            <div class="todo-container">
                <h3>发布事件</h3>
                <el-form :model="todoForm" @submit.native.prevent="addTodo">
                    <el-form-item label="标题" prop="title">
                        <el-input v-model="todoForm.title" placeholder="输入事件标题"></el-input>
                    </el-form-item>
                    <el-form-item label="内容" prop="task">
                        <el-input type="textarea" v-model="todoForm.description" placeholder="请输入事件内容"></el-input>
                    </el-form-item>
                    <el-form-item label="开始日期" prop="startDate">
                        <el-date-picker v-model="todoForm.startDate" type="datetime"
                            placeholder="选择开始日期"></el-date-picker>
                    </el-form-item>
                    <el-form-item label="截止日期" prop="endDate">
                        <el-date-picker v-model="todoForm.endDate" type="datetime"
                            placeholder="选择截止日期"></el-date-picker>
                    </el-form-item>
                    <el-form-item label="请选择事件地点" prop="location">
                        <el-select v-model="todoForm.facilityId" placeholder="请选择事件地点"  @change="onFacilityChange">
                            <el-option v-for="facility in facilities" :key="facility.id" :label="facility.name"
                                :value="facility.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="请选择事件类型">
                        <el-select v-model="todoForm.eventType" placeholder="请选择事件类型">
                            <el-option v-for="(label, value) in eventTypeDictionary" :key="value" :label="label"
                                :value="value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="酬金" prop="reward">
                        <el-input type="number"  v-model="todoForm.reward" placeholder="酬金"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" native-type="submit">发布</el-button>
                    </el-form-item>

                </el-form>
            </div>
        </div>

        <el-dialog v-model="dialogVisible" title="设施信息" @close="clearDialog" width="90%" height="100%">
            <h2 style="color: cornflowerblue;">{{ facility.name }}</h2>
            <div class="info-columns">
                <StoresList :storesList="storesList" />
                <EventsList :eventsList="eventsList" />
                <ActivitiesList :activitiesList="activitiesList" />
            </div>
        </el-dialog>
        <Rankings />

    </div>
</template>
<script setup>
import { ref, onMounted, reactive } from 'vue';
import mapImage from '@/assets/images/cduNew.png'; // 使用 import 引入图片
import { listFacilities, addFacility, updateFacility, deleteFacility } from "@/api/facility";
import StoresList from './components/StoresList.vue';
import EventsList from './components/EventsList.vue';
import ActivitiesList from './components/ActivitiesList.vue';
import Rankings from './components/Rankings.vue';
import { eventTypeDictionary } from '@/enums/event'; 
//根据商店id获取当前商店的服务和商品
import { getGoodsListByStoreId } from "@/api/product";
//根据设施id获取当前设施的事件
import { getEventByFacilityId,addEvent } from "@/api/event";
//根据设施id获取当前设施的活动
import { getActivitiesByFacilityId } from "@/api/activity";
//根据设施id获取当前设施的商店
import { getStoresByFacilityId } from "@/api/virtualStore";

//根据用户id获取用户的奖惩表
import { getRewardPunishmentByUserId } from "@/api/rewardPunishment"


import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router';
const router = useRouter();
// 检查 token 的方法
const hasToken = () => {
  // 假设 token 存储在 localStorage 中
  return localStorage.getItem('token') !== null;
};

// 事件类型字典（值为1, 2, 3, 4, 5）
// 事件类型字典（值为1到14）
// const eventTypeDictionary = {
//   1: '代取快递',
//   2: '待打印',
//   3: '求取二手物品',
//   4: '校园即送',
//   5: '代购服务',
//   6: '陪伴服务',
//   7: '学习辅导',
//   8: '拼车服务',
//   9: '房屋租赁',
//   10: '活动组织',
//   11: '二手交易',
//   12: '技能交换',
//   13: '健康咨询',
//   14: '志愿服务',
// };


// 使用 ref 定义响应式数据
const mapSrc = mapImage;
const points = ref([]); // 存储点击的相对坐标
const imageWidth = ref(0);
const imageHeight = ref(0);
const loading = ref(false);
const facilities = ref([]); // 设施列表
const facilityTitle = ref(""); // 设施名称
const goodsList = ref([]); // Store goods and services
const eventsList = ref([]); // Store events
const activitiesList = ref([]); // Store activities
const rewardPunishmentList = ref([]); // Store reward and punishment
const storesList = ref([]); // Store stores
const facility = ref({}); // 当前点击的设施
const dialogVisible = ref(false);
const queryParams = reactive({
    name: "",
    type: undefined,
});
const todoForm = ref({
    title: '',
    description: '',
    startDate: '',
    endDate: '',
    location: '', // 新增 location 属性
    facilityId: null,
    eventType: null,
    reward: null,
});
const todos = ref([]);


// 选择地点时更新 location
const onFacilityChange = (selectedId) => {
  const selectedFacility = facilities.value.find(facility => facility.id === selectedId);
  if (selectedFacility) {
    todoForm.value.location = selectedFacility.name; // 将名称赋值给 location
  } else {
    todoForm.value.location = ''; // 如果没有找到，清空 location
  }
};
const addTodo = () => {
    if (!hasToken()) {
    ElMessage({
      type: 'error',
      message: '请先登录',
    });
  }else{


    const params = {
        title: todoForm.value.title,
        description: todoForm.value.description,
        startDate: todoForm.value.startDate,
        endDate: todoForm.value.endDate,
        location: todoForm.value.location,
        facilityId: todoForm.value.facilityId,
        eventType: todoForm.value.eventType,
        reward: Number(todoForm.value.reward),
    };
    console.log("发布事件参数:", params);
    
    addEvent(params).then(response => {
        if (response.code !== 200) {
            alert("发布事件失败");
            return;
        }
        alert("发布事件成功")
        console.log("发布事件成功:", response.data);
        todos.value.push(todoForm.value);
        todoForm.value = {
            title: '',
            description: '',
            startDate: '',
            endDate: '',
            facilityId: '',
            eventType: '',
            reward: null,
        };
        dialogVisible.value = false;
    });
  }
};

// 查询设施列表
const getList = () => {
    loading.value = true;
    listFacilities(queryParams).then(response => {
        facilities.value = response.data;
        console.log("设施列表:", response.data);
        loading.value = false;
    });
};

//查询当前用户的奖惩表
const getRewardPunishment = () => {
    getRewardPunishmentByUserId().then(response => {
        console.log("当前用户的奖惩表:", response.data);
        rewardPunishmentList.value = response.data;
    });
};


// 设施数据

const clickPoints = ref([]); // 存储所有点击的坐标
const groupedPoints = ref([]); // 存储每四个点击的坐标组

const handleClick = (event) => {
    //打印照片宽高
    console.log(`Image width: ${imageWidth.value}, height: ${imageHeight.value}`);
    // const x = (event.offsetX / imageWidth.value) * 800; // 计算相对位置
    // const y = (event.offsetY / imageHeight.value) * 600; // 计算相对位置
    const x = event.offsetX
    const y = event.offsetY
    console.log(`x,y: (${x}, ${y})`);
    console.log(`event.offsetX: ,event.offsetY: (${event.offsetX}, ${event.offsetY})`);

    // 存储点击的点
    points.value.push({ x: event.offsetX, y: event.offsetY });

    // 检查点击位置是否在某个设施内部
    const clickedFacility = facilities.value.find(facility => isInsideFacility(x, y, facility));
    if (clickedFacility) {
        alert(`Clicked on: ${clickedFacility.name}`);
        //打印facility
        console.log("当前设施信息:", clickedFacility);
        //检查当前位置是否存在事件
        //TODO: 获取当前位置的事件
        getEventByFacilityId(clickedFacility.id).then(response => {
            console.log("当前设施的事件:", response.data);
            eventsList.value = response.data;
        });
        //检查当前位置是否存在活动
        //TODO: 获取当前位置的活动
        getActivitiesByFacilityId(clickedFacility.id).then(response => {
            console.log("当前设施的活动:", response.data);
            activitiesList.value = response.data;
        });
        //检查当前位置是否存在商店
        //TODO: 获取当前位置的商店
        getStoresByFacilityId(clickedFacility.id).then(response => {
            console.log("当前设施id:", clickedFacility.id);
            console.log("当前设施的商店:", response.data);
            storesList.value = response.data;
        });
        dialogVisible.value = true; // 显示弹窗





    } else {
        console.log(`Clicked at coordinates: (${x}, ${y})`);
    }
    // 存储每次点击的坐标
    clickPoints.value.push({ x, y });

    // 每四次点击组合一个坐标组
    if (clickPoints.value.length % 4 === 0) {
        const points = clickPoints.value.slice(-4); // 获取最近的四个点
        const formattedPoints = formatPoints(points);
        groupedPoints.value.push(formattedPoints); // 存储格式化的坐标组
        console.log(`Stored points group:`, formattedPoints);
    }


};

const clearDialog = () => {
    facility.value = {};
    storesList.value = [];
    eventsList.value = [];
    activitiesList.value = [];
};

const formatPoints = (points) => {
    return points.map(point => `(${point.x}, ${point.y})`);
};

// 检查点击位置是否在设施的矩形区域内
const isInsideFacility = (x, y, facility) => {
    const coordinates = parseLocation(facility.location);
    const [topLeft, topRight, bottomRight, bottomLeft] = coordinates;

    // 确定矩形的边界
    const minX = Math.min(topLeft[0], bottomLeft[0]);
    const maxX = Math.max(topRight[0], bottomRight[0]);
    const minY = Math.min(topLeft[1], topRight[1]);
    const maxY = Math.max(bottomLeft[1], bottomRight[1]);

    return x >= minX && x <= maxX && y >= minY && y <= maxY;
};

//解析位置字符串为坐标数组
const parseLocation = (location) => {
    // 去掉字符串中的空格、单引号和双引号
    console.log("原始坐标字符串:", location);
    location = location.replace(/['"\s]+/g, '');

    // 将方括号转换为圆括号
    location = location.replace(/\[/g, '(').replace(/\]/g, ')');

    const matches = location.match(/\((\d+),(\d+)\)/g);
    return matches.map(match => match.replace(/[()]/g, '').split(',').map(Number));
};
const getFacilityStyle = (facility) => {
    const coordinates = parseLocation(facility.location);
    if (!coordinates) {
        console.warn(`Invalid location for facility: ${facility.name}`);
        return {}; // 返回空样式以避免错误
    }

    // 获取多边形的边界
    const left = Math.min(...coordinates.map(coord => coord[0]));
    const top = Math.min(...coordinates.map(coord => coord[1]));
    const right = Math.max(...coordinates.map(coord => coord[0]));
    const bottom = Math.max(...coordinates.map(coord => coord[1]));

    // 计算多边形的宽度和高度
    const width = right - left;
    const height = bottom - top;

    // 使用 clipPath 定义多边形
    const polygonPoints = coordinates.map(coord => {
        return `${(coord[0] - left) / width * 100}% ${(coord[1] - top) / height * 100}%`;
    }).join(', ');

    return {
        position: 'absolute',
        left: left + 'px',
        top: top + 'px',
        width: width + 'px',
        height: height + 'px',
        backgroundColor: 'rgba(255, 0, 0, 0.3)', // 半透明背景
        border: '1px solid red', // 红色边框
        borderRadius: '1px',
        clipPath: `polygon(${polygonPoints})` // 使用 clipPath 定义多边形
    };
};


// 获取图片尺寸
const setImageDimensions = () => {
    const img = new Image();
    img.src = mapSrc;
    img.onload = () => {
        imageWidth.value = img.width;
        imageHeight.value = img.height;
    };
};

// 在组件挂载时获取图片尺寸
onMounted(() => {
    setImageDimensions();
    getRewardPunishment();
});

// 初始化设施列表
getList();
</script>
<style>
.flex-container {
    display: flex;
    min-width: 1420px; 
    max-width: 1600px;
    /* width: 95vw; */
    align-items: flex-start;
    flex-direction: column;
}

.map-container {
    display: flex;
    position: relative;
    width: 100%;
    flex-direction: row;
    /* 从左向右排列 */

    /* 根据图片宽度自适应 */
    height: auto;
    /* 根据图片高度自适应 */
    /* 允许左右滑动 */
    
}

.todo-container {
    margin-top: 5px;
    /* 地图与卡片容器之间的间距 */
    margin-left: 10px;
    background-color: white;
    border: 1px solid #ccc;
    min-width: 200px;
    max-width: 300px;
    border-radius: 8px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
    background-color: #f9f9f9;
    padding: 15px;
}

.map-image {
    display: block;
    /* 确保图片是块级元素 */
    width: 1077px;
    /* 适应容器宽度 */
    max-height: 100%;
    /* 适应容器 */
}

.marker {
    position: absolute;
    width: 20px;
    height: 20px;
    background-color: red;
    border-radius: 50%;
    transform: translate(-50%, -50%);
}

.facility {
    position: absolute;
    pointer-events: none;
    /* Disable pointer events for facilities */
}

.facility-name {
    color: white;
    font-weight: bold;
    font-size: 15px;
    text-align: center;
    margin-top: 5px;
}

.card-containers {
    margin-top: 20px;
    /* 地图与卡片容器之间的间距 */
    background-color: white;
    border: 1px solid #ccc;
    min-width: 1057px;
    max-width: 1057px;
    /* 卡片容器的最大宽度 */
    border-radius: 8px;
    padding: 10px;
    flex-grow: 1;
    /* 使卡片容器占据剩余空间 */
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}


.info-columns {
    display: flex;
    /* 使用 flexbox 布局 */
    justify-content: space-between;
    /* 分散排列 */
}

.info-column {
    flex: 1;
    /* 每列占相等宽度 */
    margin: 0 10px;
    /* 列间距 */
}

.stores-list,
.events-list,
.activities-list {
    max-height: 800px;
    /* 设置最大高度 */
    overflow-y: auto;
    /* 纵向滚动条 */
    margin-bottom: 15px;
    /* 每个部分之间的间距 */
}

.card {
    margin-bottom: 10px;
    padding: 10px;
    border: 2px solid #eee;
    border-radius: 4px;
}

.card h4 {
    margin: 0;
}

.card p {
    margin: 5px 0 0;
}

.el-form-item {
    margin-bottom: 20px;
}

.el-input,
.el-select,
.el-date-picker {
    border-radius: 4px;
    box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
}


</style>